<template>
  <!-- 新增编辑 -->
  <a-modal
    :width="600"
    :maskClosable="false"
    :visible="props.visible"
    :confirm-loading="loading"
    :forceRender="true"
    :title="props.isUpdate ? '修改工作流' : '创建工作流'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
    class="common-modal"
    @close="updateVisible(false)"
  >
    <div>
      <a-form ref="userFormRef" :model="form" :rules="rules" :label-col="labelCol">
        <a-form-item label="流程名称" name="name">
          <a-input v-model:value="form.name" />
        </a-form-item>
        <a-form-item label="应用图标:" name="icon">
          <a-upload
            name="file"
            :multiple="false"
            :maxCount="1"
             v-model:file-list="form.iconList"
             :default-file-list="form.iconList"
            :action="icon.fileUploadUrl"
             :headers="icon.headers"
            list-type="picture-card"
            :before-upload="beforeUpload"
            accept=".jpeg,.jpg,.png,.tif,.jfif,.webp,.pjp,.apng,.pjpeg,.avif,.ico,.tiff,.bmp,.xbm,.jxl,.jpeg,.svgz,.gif,.svg"
            @preview="handlePreviewPhoto"
            @download="downloadPhoto"
            @change="info => handleFileChange(info)"
           :showUploadList="{
              showDownloadIcon: true
            }"
          >
      
         
            
              <plus-outlined v-if="form.iconList?.length == 0" ></plus-outlined>
            
          </a-upload>
        </a-form-item>
        <a-form-item label="描述" name="descr">
          <a-textarea v-model:value="form.descr" />
        </a-form-item>
        <!-- <div>{{ isUpdate ? '编辑模型' : '新建模型' }}</div> -->
      </a-form>
    </div>
  </a-modal>
</template>

<script setup name="UserAddEdit">
import { ref, onMounted, reactive, computed } from 'vue';
import { message } from 'ant-design-vue';
import { FileApi, FileUploadUrl as fileUploadUrlPrefix } from '@/views/system/backend/file/api/FileApi';
import { FlowApi } from '@/views/super/airag/aiflow/api/FlowApi';
import { getToken } from '@/utils/token-util';
import { API_BASE_PREFIX } from '@/config/setting';
const props = defineProps({
  visible: Boolean,
  data: Object,
  isUpdate: false
});
const rules = ref({
  name: [{ required: true, message: '请输入流程名称' }]
});
const emits = defineEmits(['update:visible', 'done']);
const labelCol = { style: { width: '110px' } };

// 弹框加载
const loading = ref(false);
// 是否是编辑状态

// 表单数据
const form = ref({
  iconList: []
});

// 图标上传预览地址
const icon = reactive({
  // 上传文件的url
  fileUploadUrl: `${API_BASE_PREFIX}${fileUploadUrlPrefix}?secretFlag=N`,
  filePreviewUrl: `${API_BASE_PREFIX}/sysFileInfo/public/preview?fileId=`,
  // 上传文件时候要带header
  headers: {
    Authorization: getToken()
  }
});

// 是否展示图片预览
const previewVisible = ref(false);
// 图片地址
const previewImage = ref(null);

//上传之前的回调
const beforeUpload = file => {
  const isJpgOrPng =
    file.type === 'image/jpeg' ||
    file.type === 'image/jpg' ||
    file.type === 'image/png' ||
    file.type === 'image/tif' ||
    file.type === 'image/jfif' ||
    file.type === 'image/webp' ||
    file.type === 'image/pjp' ||
    file.type === 'image/apng' ||
    file.type === 'image/pjpeg' ||
    file.type === 'image/avif' ||
    file.type === 'image/ico' ||
    file.type === 'image/tiff' ||
    file.type === 'image/bmp' ||
    file.type === 'image/xbm' ||
    file.type === 'image/jxl' ||
    file.type === 'image/svgz' ||
    file.type === 'image/gif' ||
    file.type === 'image/svg';
  if (!isJpgOrPng) {
    message.error('只能上传图片!');
    return Upload.LIST_IGNORE; //阻止列表展现
  }
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    message.error('图片大小不能超过5MB!');
  }
  return isJpgOrPng && isLt5M;
};

// 上传成功
const handleFileChange = info => {
  if (info.file.status === 'done') {
    // 设置临时fileList的值
    form.value.icon = info.file.response.data.fileId;
    message.success(`${info.file.name} 图片上传成功`);
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 图片上传失败`);
  }
};

// 点击预览图片
const handlePreviewPhoto = async file => {
  previewImage.value = file.url || file.preview || file.thumbUrl;
  previewVisible.value = true;
};

//下载图片
const downloadPhoto = file => {
  let id = file.response ? file.response.data.fileId : file.uid;
  FileApi.download({ token: getToken(), fileId: id });
};

// ref
const userFormRef = ref(null);

onMounted(async () => {
  if (props.data) {
    form.value = { ...props.data };
    if(form.value.icon) {
      // 设置图标
      setFileList("iconList", form.value.icon);
    }else {
      form.value.iconList = [];
    }
    // isUpdate.value = true;
  } else {
    // isUpdate.value = false;
  }
});
// 设置文件列表
    const setFileList = (name, fileId) => {
      FileApi.getAntdVInfo({ fileId: fileId }).then(res => {
        res.uid = fileId;
        form.value[name] = [res];
      });
    };
// 更改弹框状态
const updateVisible = value => {
  emits('update:visible', value);
};

// 点击保存
const save = async () => {
  userFormRef.value.validate().then(async valid => {
    if (valid) {
      loading.value = true;
      Object.assign(props.data, form.value);
      // 编辑操作
      if (props.isUpdate) {
        FlowApi.edit(props.data)
          .then(async result => {
            loading.value = false;
            message.success(result.message);
            emits('done', 'ok');
          })
          .catch(() => {
            loading.value = false;
          });
      } else {
        emits('done', 'ok');
      }
    }
  });
};
</script>

<style></style>
